package com.yemast.readertesst

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * <p>文件描述</p>
 * 用户名:yema
 * 时间:2019/9/18   16:52
 */
class GridSpacingItemDecoration(var spacing: Int = 10) : RecyclerView.ItemDecoration() {

    private var mOrientation = 0
    private var spanCount = 0
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view) // item position

        if (parent.layoutManager is GridLayoutManager) {
            val gridLayoutManager = parent.layoutManager as GridLayoutManager
            spanCount = gridLayoutManager.spanCount
        }

        when (parent.layoutManager) {
            is GridLayoutManager -> {
                if (position < spanCount) {
                    if (position % spanCount === spanCount - 1) {//顶部最右
                        outRect.set(spacing, 0, 0, spacing)
                    } else if (position % spanCount == 0) {//最左边
                        outRect.set(0, 0, 0, spacing);
                    } else {
                        outRect.set(spacing, 0, 0, spacing);
                    }
                } else {
                    if (position % spanCount === spanCount - 1) {//顶部最右
                        outRect.set(spacing, 0, 0, spacing)
                    } else if (position % spanCount == 0) {//最左边
                        outRect.set(0, 0, 0, spacing);
                    } else {
                        outRect.set(spacing, 0, 0, spacing);
                    }
                }

            }
            is LinearLayoutManager -> {
                mOrientation = (parent.layoutManager as LinearLayoutManager).orientation
                when (mOrientation) {
                    LinearLayoutManager.HORIZONTAL -> {
                        if (position != 0) {
                            outRect.set(spacing, 0, 0, 0);
                        }
                    }
                    LinearLayoutManager.VERTICAL -> {
                        if (position != 0) {
                            outRect.set(0, 0, 0, spacing);
                        }
                    }
                }
            }
        }

    }
}